package com.example.encryptedsharedpreferences

import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.encryptedsharedpreferences.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
    }

    /**
     * 加密
     */
    fun encode(view: View) {

        // TODO: 2021/7/14 0014 sp 加密
        val sp: SharedPreferences = getSharedPreferences("test", MODE_PRIVATE)

        val esp = EncryptedSharedPreferences(sp, EncryptionImpl())
        val edit = esp.edit()
        /*edit.putString("key1", "呵呵哒")
        edit.apply()*/
        edit.putInt("key2", 1000)
        edit.apply()
        edit.putBoolean("key3", true)
        edit.apply()
        edit.putFloat("key4", 3.5f)
        edit.apply()
        edit.putLong("key5", 100000L)
        edit.apply()

        val set = HashSet<String>()
        set.add("123456")
        set.add("qwert")
        edit.putStringSet("key6", set)
        edit.apply()

    }

    /**
     * 解密
     */
    fun decode(view: View) {

        // TODO: 2021/7/14 0014 sp 解密
        val sp = getSharedPreferences("test", MODE_PRIVATE)
        val esp = EncryptedSharedPreferences(sp, EncryptionImpl())
        val int = esp.getInt("key2", -1)
        Toast.makeText(this, int.toString(), Toast.LENGTH_SHORT).show()
        val boolean = esp.getBoolean("key3", false)
        Log.i("SYM", "key3 == " + boolean)
        Log.i("SYM", "key4 == " + esp.getFloat("key4", -1.0f))
        Log.i("SYM", "key5 == " + esp.getLong("key5", -1L))
        Log.i("SYM", "key6 == " + esp.getStringSet("key6", null))

        val all = esp.all
        Log.i("SYM", "all == " + all.toList().toString())
    }
}